<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">排班管理</span>
          <div class="header-actions">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['scheduling:schedule:add']"
            >新增排班</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
        <el-form-item label="医生姓名" prop="doctorName">
          <el-input
              v-model="queryParams.doctorName"
              placeholder="请输入医生姓名"
              clearable
              style="width: 180px"
              @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
          >
            <el-option
                v-for="dict in status_options"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button
              type="danger"
              plain
              icon="Delete"
              @click="handleBatchDelete"
              :disabled="multiple"
              v-hasPermi="['scheduling:schedule:remove']"
          >删除</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
          v-loading="loading"
          :data="scheduleList"
          @selection-change="handleSelectionChange"
          class="schedule-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="医生姓名" align="center" prop="doctorName" min-width="120" />
        <el-table-column label="可预约最大数量" align="center" prop="maxCapacity" min-width="130" />
        <el-table-column label="开始时间" align="center" prop="startTime" min-width="120">
          <template #default="scope">
            <span class="time-text">{{ scope.row.startTime || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" min-width="120">
          <template #default="scope">
            <span class="time-text">{{ scope.row.endTime || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排班日期" align="center" prop="scheduleDate" min-width="120">
          <template #default="scope">
            <span class="date-text">{{ parseTime(scope.row.scheduleDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="挂号费用" align="center" prop="appointmentFee" min-width="100">
          <template #default="scope">
            <span class="fee-text">¥{{ scope.row.appointmentFee || '0.00' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" min-width="80">
          <template #default="scope">
            <el-tag
                :type="scope.row.status === '0' ? 'success' : 'danger'"
                effect="light"
            >
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="150" fixed="right">
          <template #default="scope">
            <el-button
                link
                type="primary"
                icon="Edit"
                size="small"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['scheduling:schedule:edit']"
            >修改</el-button>
            <el-button
                link
                type="danger"
                icon="Delete"
                size="small"
                @click="handleDelete(scope.row)"
                v-hasPermi="['scheduling:schedule:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改排班对话框 -->
    <el-dialog
        :title="title"
        v-model="open"
        width="600px"
        append-to-body
        class="schedule-dialog"
        :close-on-click-modal="false"
    >
      <el-form ref="scheduleRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="医生姓名" prop="doctorId">
              <el-select
                  v-model="form.doctorId"
                  placeholder="请选择医生"
                  filterable
                  clearable
                  style="width: 100%"
                  @change="handleDoctorChange"
              >
                <el-option
                    v-for="doctor in doctorList"
                    :key="doctor.doctorId"
                    :label="doctor.doctorName"
                    :value="doctor.doctorId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="挂号费用" prop="appointmentFee">
              <el-input
                  v-model="form.appointmentFee"
                  placeholder="请输入挂号费用"
                  type="number"
                  min="0"
                  step="0.01"
              >
                <template #prefix>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="可预约数量" prop="maxCapacity">
              <el-input
                  v-model="form.maxCapacity"
                  placeholder="请输入可预约最大数量"
                  type="number"
                  min="1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                    v-for="dict in status_options"
                    :key="dict.value"
                    :label="dict.value"
                >{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker
                  clearable
                  v-model="form.startTime"
                  value-format="HH:mm:ss"
                  placeholder="请选择开始时间"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker
                  clearable
                  v-model="form.endTime"
                  value-format="HH:mm:ss"
                  placeholder="请选择结束时间"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="排班日期" prop="scheduleDate">
          <el-date-picker
              clearable
              v-model="form.scheduleDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择排班日期"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Schedule">
import { listSchedule, getSchedule, delSchedule, addSchedule, updateSchedule } from "@/api/scheduling/schedule"
import { listDoctor } from "@/api/medical/doctor"
import { parseTime } from "../../../utils/ruoyi.js";

const { proxy } = getCurrentInstance()

const scheduleList = ref([])
const doctorList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 状态字典
const status_options = ref([
  { value: '0', label: '正常' },
  { value: '1', label: '停用' }
])

// 初始化表单数据
const initFormData = () => ({
  scheduleId: null,
  doctorId: null,
  doctorName: null,
  maxCapacity: null,
  startTime: null,
  endTime: null,
  scheduleDate: null,
  appointmentFee: null,
  status: '0'
})

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  doctorName: null,
  status: null,
})

const form = ref(initFormData())

const rules = ref({
  doctorId: [
    { required: true, message: "请选择医生", trigger: "change" }
  ],
  maxCapacity: [
    { required: true, message: "可预约最大数量不能为空", trigger: "blur" },
    { pattern: /^[1-9]\d*$/, message: "请输入正确的数量", trigger: "blur" }
  ],
  startTime: [
    { required: true, message: "开始时间不能为空", trigger: "change" }
  ],
  endTime: [
    { required: true, message: "结束时间不能为空", trigger: "change" }
  ],
  scheduleDate: [
    { required: true, message: "排班日期不能为空", trigger: "change" }
  ],
  appointmentFee: [
    { required: true, message: "挂号费用不能为空", trigger: "blur" },
    { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额格式", trigger: "blur" }
  ],
  status: [
    { required: true, message: "状态不能为空", trigger: "change" }
  ]
})

/** 获取状态标签 */
function getStatusLabel(status) {
  const option = status_options.value.find(item => item.value === status)
  return option ? option.label : status
}

/** 查询排班列表 */
function getList() {
  loading.value = true
  listSchedule(queryParams.value).then(response => {
    scheduleList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
  }).catch(error => {
    console.error('获取排班列表失败:', error)
    scheduleList.value = []
    total.value = 0
    loading.value = false
  })
}

/** 获取医生列表 */
function getDoctors() {
  listDoctor({ pageSize: 1000 }).then(response => {
    doctorList.value = response.rows || []
  }).catch(error => {
    console.error('获取医生列表失败:', error)
    doctorList.value = []
  })
}

/** 医生选择变化 */
function handleDoctorChange(doctorId) {
  if (doctorId) {
    const selectedDoctor = doctorList.value.find(doctor => doctor.doctorId === doctorId)
    if (selectedDoctor) {
      form.value.doctorName = selectedDoctor.doctorName
    }
  } else {
    form.value.doctorName = null
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = initFormData()
  if (proxy.$refs["scheduleRef"]) {
    proxy.$refs["scheduleRef"].resetFields()
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  if (proxy.$refs["queryRef"]) {
    proxy.$refs["queryRef"].resetFields()
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.scheduleId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getDoctors()
  open.value = true
  title.value = "添加排班"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const scheduleId = row.scheduleId
  getDoctors()
  getSchedule(scheduleId).then(response => {
    const data = response.data
    form.value = {
      ...initFormData(),
      ...data
    }
    open.value = true
    title.value = "修改排班"
  }).catch(error => {
    console.error('获取排班详情失败:', error)
    proxy.$modal.msgError("获取排班详情失败")
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scheduleRef"].validate(valid => {
    if (valid) {
      const submitData = {
        ...form.value
      }

      // 移除不需要的字段
      delete submitData.doctorName

      const request = form.value.scheduleId
          ? updateSchedule(submitData)
          : addSchedule(submitData)

      request.then(response => {
        proxy.$modal.msgSuccess(form.value.scheduleId ? "修改成功" : "新增成功")
        open.value = false
        getList()
      }).catch(error => {
        console.error('提交失败:', error)
        proxy.$modal.msgError("操作失败")
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const scheduleIds = row.scheduleId || ids.value
  if (!scheduleIds || scheduleIds.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的数据")
    return
  }

  proxy.$modal.confirm('是否确认删除选中的排班数据？').then(function() {
    return delSchedule(scheduleIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 批量删除 */
function handleBatchDelete() {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的数据")
    return
  }
  // 传递选中的 IDs 给 handleDelete 函数
  handleDelete({ scheduleId: ids.value })
}

// 页面加载时初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.box-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #e6e8eb;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
}

.header-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 16px;
  background: #409eff;
  margin-right: 8px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-form {
  margin-bottom: 0;
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.schedule-table {
  margin-top: 0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.time-text, .date-text {
  font-weight: 500;
  font-size: 14px;
}

.time-text {
  color: #409eff;
  background: #f0f7ff;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

.date-text {
  color: #67c23a;
  background: #f0f9ff;
  padding: 4px 8px;
  border-radius: 4px;
  display: inline-block;
}

.fee-text {
  color: #e6a23c;
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table) {
  width: 100%;
}

:deep(.el-table .cell) {
  padding: 12px 8px;
  font-size: 13px;
}

:deep(.el-table thead th) {
  background: #f8fafc !important;
  color: #606266;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table th > .cell) {
  padding: 12px 8px;
}

:deep(.schedule-dialog .el-form-item) {
  margin-bottom: 20px;
}

:deep(.schedule-dialog .el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.schedule-dialog .el-radio-group) {
  width: 100%;
}

:deep(.schedule-dialog .el-radio) {
  margin-right: 20px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 20px;
  padding: 20px 20px 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 6px;
}

:deep(.el-date-editor .el-input__inner) {
  border-radius: 6px;
}

:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
}
</style>